<template>
  <el-dialog
    v-model="dialogVisible"
    title="分类管理"
    width="600px"
    @close="handleClose"
  >
    <div class="category-manage">
      <!-- 新建分类表单 -->
      <el-form :model="newCategory" :inline="true" class="add-form">
        <el-form-item label="分类名称">
          <el-input
            v-model="newCategory.name"
            placeholder="请输入分类名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="newCategory.color" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新建
          </el-button>
        </el-form-item>
      </el-form>

      <el-divider />

      <!-- 分类列表 -->
      <div class="category-list">
        <div
          v-for="category in categories"
          :key="category.categoryId"
          class="category-item"
        >
          <div class="category-info">
            <span
              class="color-dot"
              :style="{ backgroundColor: category.color }"
            ></span>
            <span class="name">{{ category.name }}</span>
            <el-tag size="small">{{ category.taskCount }} 个任务</el-tag>
          </div>
          <div class="category-actions">
            <el-button
              size="small"
              @click="handleEdit(category)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(category)"
              :disabled="category.name === '其他'"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑分类对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑分类"
      width="400px"
      append-to-body
    >
      <el-form :model="editCategory" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="editCategory.name" />
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="editCategory.color" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">确定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createCategory, updateCategory, deleteCategory } from '../api/category'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  categories: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'refresh'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const newCategory = ref({
  name: '',
  color: '#409EFF'
})

const editDialogVisible = ref(false)
const editCategory = ref({
  categoryId: null,
  name: '',
  color: ''
})

// 新建分类
const handleAdd = async () => {
  if (!newCategory.value.name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }

  try {
    await createCategory(newCategory.value)
    ElMessage.success('创建成功')
    
    // 重置表单
    newCategory.value = {
      name: '',
      color: '#409EFF'
    }
    
    emit('refresh')
  } catch (error) {
    console.error('创建分类失败:', error)
  }
}

// 编辑分类
const handleEdit = (category) => {
  editCategory.value = {
    categoryId: category.categoryId,
    name: category.name,
    color: category.color
  }
  editDialogVisible.value = true
}

// 更新分类
const handleUpdate = async () => {
  if (!editCategory.value.name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }

  try {
    await updateCategory(editCategory.value.categoryId, {
      name: editCategory.value.name,
      color: editCategory.value.color
    })
    
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    emit('refresh')
  } catch (error) {
    console.error('更新分类失败:', error)
  }
}

// 删除分类
const handleDelete = async (category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${category.name}"吗？该分类下的任务将移至"其他"分类。`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteCategory(category.categoryId)
    ElMessage.success('删除成功')
    emit('refresh')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
    }
  }
}

const handleClose = () => {
  emit('update:modelValue', false)
}
</script>

<style scoped>
.category-manage {
  padding: 10px 0;
}

.add-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.category-list {
  max-height: 400px;
  overflow-y: auto;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.category-item:hover {
  background-color: #f5f7fa;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.color-dot {
  width: 16px;
  height: 16px;
  border-radius: 50%;
}

.name {
  font-size: 14px;
  font-weight: 500;
}

.category-actions {
  display: flex;
  gap: 8px;
}
</style>
